package edu.wright.ceg4980.year2013.keyboard;

import java.awt.BorderLayout;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ExecutionException;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

@SuppressWarnings("serial")
public class SaveScreen extends JPanel {
	private JTextArea infoTextArea;
	
	public SaveScreen() {
		super(new BorderLayout());
		setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		
		infoTextArea = new JTextArea();
		infoTextArea.setEditable(false);
		infoTextArea.setLineWrap(true);
		infoTextArea.setWrapStyleWord(true);
		infoTextArea.setBackground(getBackground());
		
		add(infoTextArea, BorderLayout.CENTER);
	}
	
	public void saveToFile(final String password, final KeySequenceData[] data) {
		infoTextArea.setText("Please wait as we save your data to a file...");
		
//TODO need to have the user enter their email username and password to send the data via email
		(new SwingWorker<Void, Void>() {
			@Override
			protected void done() {
				try {
					get();
				} catch (InterruptedException ex) {
				} catch (ExecutionException ex) {
					infoTextArea.setText("Error while saving!");
					ex.printStackTrace();
					return;
				}
				
				infoTextArea.setText("Thank you for using our Keyboard Dynamics Data Collector! Click 'Next' or 'Restart' to return back to the Welcome screen.");
			}
			
			@Override
			protected Void doInBackground() throws IOException {
				final String FILE_NAME = ?;
				
				PrintWriter pw = new PrintWriter(new File(FILE_NAME));
				pw.printf("%s\n", password);
				pw.printf("%d\n", data.length);
				for (KeySequenceData ksd : data) {
					pw.printf("%d %d\n", ksd.keyPresses.length, ksd.keyReleases.length);
					for (KeyData kd : ksd.keyPresses) {
						pw.printf("%d %d\n", kd.keyCode, kd.time);
					}
					
					for (KeyData kd : ksd.keyReleases) {
						pw.printf("%d %d\n", kd.keyCode, kd.time);
					}
				}

				pw.flush();
				pw.close();
				return null;
			}
		}).execute();
	}
}
